//
//  NetworkTools.swift
//  weibo
//
//  Created by mac on 15/12/20.
//  Copyright © 2015年 rong. All rights reserved.
//

import AFNetworking

let dataErrorDomain = "com.baidu.data.error"

//枚举任意类型
enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
}
//网络请求的处理层 以后的网络请求 都适用这个类 来进行数据的获取
class NetworkTools: AFHTTPSessionManager {
    //单利对象
    static let sharedTools: NetworkTools = {
    //设置baseurl
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    //网络封装
    func requestJSONDict(method:HTTPMethod,urlString:String,parameters:[String:AnyObject],finished:(dict:[String:AnyObject]?,error:NSError?)->()) {
        if method == HTTPMethod.POST {
        POST(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            }, success: { (_, result) -> Void in
                //请求成功的回调
                guard let dict = result as? [String:AnyObject] else {
                //不能够转换为字典数据
                    //执行失败的回调
                    let myError = NSError(domain: dataErrorDomain, code: -1000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
                    print(myError)
                    finished(dict: nil, error: myError)
                    return
                }
                //执行成功的回调
                finished(dict: dict, error: nil)
            }, failure: { (_, error) -> Void in
                //执行失败的回调
                finished(dict: nil, error: error)
                print(error)
        })
        }else {
        GET(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            }, success: { (_, result) -> Void in
                //请求成功的回调
                guard let dict = result as? [String:AnyObject] else {
                //不能够转换为字典数据
                    let myError = NSError(domain: dataErrorDomain, code: -1000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
                    print(myError)
                    finished(dict: nil, error: myError)
                    return
                }
                //执行成功的回调
                finished(dict: dict, error: nil)
            }, failure: { (_, error) -> Void in
                //执行失败的回调
                finished(dict: nil, error: error)
                
                print(error)
        })
        }
    }
}
